<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\model\Transfer;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use think\Db;

/**
 * 论坛内部人员逻辑
 */
class BbsUser extends AdminBase
{

    /**
     * 获取论坛内部人员信息
     */
    public function getMemberInfo($where = [], $field = true)
    {

        $info = $this->modelMember->getInfo($where, $field);

        $info['leader_nickname'] = $this->modelMember->getValue(['id' => $info['leader_id']], 'nickname');
        return $info;
    }

    /**
     * 获取论坛内部人员列表
     */
    public function getMemberList($data = [], $field = 'a.*,b.username as leader_nickname', $order = '', $paginate = DB_LIST_ROWS)
    {
        $where = [];
        if (!empty($data['date1'])) {
            if (!empty($data['date2'])) {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
            } else {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), time()]];
            }
        }
        if (!empty($data['uid'])) {
            $where['a.id'] = $data['uid'];
        }
        if (!empty($data['username'])) {
            $where['a.username'] = $data['username'];
        }
        if (!empty($data['mobile'])) {
            $where['a.mobile'] = $data['mobile'];
        }

	
        $where['a.status'] = 1;
        $where['a.is_inside'] = 2;

            $list = $this->modelMember->alias('a')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);

            $count = $this->modelMember->alias('a')->where($where)->count();


        return ['count' => $count, 'list' => $list];

    }


    /**
     * 导出论坛内部人员列表
     */
    public function exportMemberList($data = [], $field = 'a.*', $order = 'id asc')
    {

        set_time_limit(0);
        $where = $where1 = [];
        if (!empty($data['date1'])) {
            if (!empty($data['date2'])) {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
            } else {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), time()]];
            }
        }
        if (!empty($data['uid'])) {
            $where['a.id'] = $data['uid'];
        }
        if (!empty($data['username'])) {
            $where['a.username'] = ['like', '%' . $data['username'] . '%'];
        }
        if (!empty($data['mobile'])) {
            $where['a.mobile'] = $data['mobile'];
        }
      if (!empty($data['leader_id'])  ) {
         
          $where['b.username'] = $data['leader_id'];
          $where1['b.username'] = $data['leader_id'];
          
        }

        $where['a.status'] = 1;
        $where['a.is_inside'] = 2;
        if (!empty($where1)) {
            $list = $this->modelMember->alias('a')->field($field)->join('__MEMBER__ b', 'a.leader_id = b.id')->where($where)->order($order)->select();
        } else {
            $list = $this->modelMember->alias('a')->field($field)->where($where)->order($order)->select();
        }


        foreach ($list as $k => $v) {
			$list[$k]['k'] = $k+1;
            $list[$k]['wal'] = $v->is_excel_wallet ? '是' : '否';
            $list[$k]['leader_nickname'] = $v->leader_nickname;
            $list[$k]['add_time'] = date('Y-m-d H:i:s', $v->create_time);
            $list[$k]['ke'] = empty($v->wallet()[0]) ? 0 : $v->wallet()[0]['balance'];
            $list[$k]['shan'] = empty($v->wallet()[1]) ? 0 : $v->wallet()[1]['balance'];
            $list[$k]['gc'] = empty($v->wallet()[2]) ? 0 : $v->wallet()[2]['balance'];
        }

//        dd(json_decode(json_encode($list),true));
        $titles = "序号,UID,用户名,手机,注册时间,分享账号,可用,闪兑,GC,是否导入钱包,";
        $keys = "k,id,username,mobile,add_time,leader_nickname,ke,shan,gc,wal";

        action_log('导出', '导出论坛内部人员列表');

        export_excel($titles, $keys, $list, '论坛内部人员列表');
    }

    /**
     * 获取论坛内部人员列表搜索条件
     */
    public function getWhere($data = [])
    {

        $where = [];

        !empty($data['search_data']) && $where['m.nickname|m.username|m.email|m.mobile'] = ['like', '%' . $data['search_data'] . '%'];

        if (!is_administrator()) {

            $member = session('member_info');

            if ($member['is_share_member']) {

                $ids = $this->getInheritMemberIds(MEMBER_ID);

                $ids[] = MEMBER_ID;

                $where['m.leader_id'] = ['in', $ids];

            } else {

                $where['m.leader_id'] = MEMBER_ID;
            }
        }

        return $where;
    }

    /**
     * 获取存在继承关系的论坛内部人员ids
     */
    public function getInheritMemberIds($id = 0, $data = [])
    {

        $member_id = $this->modelMember->getValue(['id' => $id, 'is_share_member' => DATA_NORMAL], 'leader_id');

        if (empty($member_id)) {

            return $data;
        } else {

            $data[] = $member_id;

            return $this->getInheritMemberIds($member_id, $data);
        }
    }

    /**
     * 获取论坛内部人员的所有下级论坛内部人员
     */
    public function getSubMemberIds($id = 0, $data = [])
    {

        $member_list = $this->modelMember->getList(['leader_id' => $id], 'id', 'id asc', false);

        foreach ($member_list as $v) {

            if (!empty($v['id'])) {

                $data[] = $v['id'];

                $data = array_unique(array_merge($data, $this->getSubMemberIds($v['id'], $data)));
            }

            continue;
        }

        return $data;
    }

    /**
     * 论坛内部人员添加到用户组
     */
    public function addToGroup($data = [])
    {

        $url = url('memberList');

        if (SYS_ADMINISTRATOR_ID == $data['id']) {

            return [RESULT_ERROR, '天神不能授权哦~', $url];
        }

        $where = ['member_id' => ['in', $data['id']]];

        $this->modelAuthGroupAccess->deleteInfo($where, true);

        if (empty($data['group_id'])) {

            return [RESULT_SUCCESS, '论坛内部人员授权成功', $url];
        }

        $add_data = [];

        foreach ($data['group_id'] as $group_id) {

            $add_data[] = ['member_id' => $data['id'], 'group_id' => $group_id];
        }

        if ($this->modelAuthGroupAccess->setList($add_data)) {

            action_log('授权', '论坛内部人员授权，id：' . $data['id']);

            $this->logicAuthGroup->updateSubAuthByMember($data['id']);

            return [RESULT_SUCCESS, '论坛内部人员授权成功', $url];
        } else {

            return [RESULT_ERROR, $this->modelAuthGroupAccess->getError()];
        }
    }

    /**
     * 论坛内部人员添加
     */
    public function memberAdd($data = [])
    {

        $validate_result = $this->validateMember->scene('add')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateMember->getError()];
        }

        $url = url('memberList');

        $data['nickname'] = $data['username'];
        $data['pin_password'] = md5($data['pin_password'] . 'pin');
        $data['is_inside'] = 2;
        Db::startTrans();
        try {
            $result = $this->modelMember->setInfo($data);
            UserAccount::addWallet($result);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return [RESULT_ERROR, $e->getMessage()];
        }

        $result && action_log('新增', '新增论坛内部人员，username：' . $data['username']);

        return $result ? [RESULT_SUCCESS, '论坛内部人员添加成功', $url] : [RESULT_ERROR, $this->modelMember->getError()];
    }

    /**
     * 论坛内部人员编辑
     */
    public function memberEdit($data = [])
    {

        $validate_result = $this->validateMember->scene('edit')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateMember->getError()];
        }

        Db::startTrans();
        try {


            if (!$data['password']) {
                unset($data['password']);
            }
            if (!$data['pin_password']) {
                unset($data['pin_password']);
            } else {
                $data['pin_password'] = md5($data['pin_password'] . 'pin');
            }
            $url = url('memberList');

            $result = $this->modelMember->setInfo($data);

            $result && action_log('编辑', '编辑论坛内部人员，id：' . $data['id']);
            Db::commit();
            return $result ? [RESULT_SUCCESS, '论坛内部人员编辑成功', $url] : [RESULT_ERROR, $this->modelMember->getError()];
        } catch (\Exception $e) {
            return [RESULT_ERROR, $e->getMessage()];
        }

    }



    /**
     * 设置论坛内部人员信息
     */
    public function setMemberValue($where = [], $field = '', $value = '')
    {

        return $this->modelMember->setFieldValue($where, $field, $value);
    }

    /**
     * 论坛内部人员删除
     */
    public function memberDel($where = [])
    {

        $url = url('memberList');

        if (SYS_ADMINISTRATOR_ID == $where['id'] || MEMBER_ID == $where['id']) {

            return [RESULT_ERROR, '天神和自己不能删除哦~', $url];
        }

        $result = $this->modelMember->deleteInfo($where);

        $result && action_log('删除', '删除论坛内部人员，where：' . http_build_query($where));

        return $result ? [RESULT_SUCCESS, '论坛内部人员删除成功', $url] : [RESULT_ERROR, $this->modelMember->getError(), $url];
    }





    /**
     * 锁定
     */
    public function update_info($where = [])
    {

        //dd($where);

        $result = $this->modelMember->setInfo($where);


        return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, '操作失败'];
    }

    /**
     * 设置论坛内部人员信息
     */
    public function member_level($data)
    {
        $member = new \app\common\model\Member();

        echo json_encode($member->member_tree($data['id']), JSON_UNESCAPED_UNICODE);
        die;
    }


}
